package com.system.travel.common.security;

import com.system.travel.modules.system.entity.SysUser;
import com.system.travel.modules.system.service.SysUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
import java.util.List;
import java.util.stream.Collectors;

/**
 * UserDetailsService实现类
 *
 * @author lucas
 * @date 2024/01/01
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        SysUser user = userService.getByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 获取用户详细信息
        Map<String, Object> userInfo = userService.getUserInfo(user.getId());
        
        // 获取权限列表
        @SuppressWarnings("unchecked")
        List<Map<String, Object>> permissions = (List<Map<String, Object>>) userInfo.get("permissions");
        List<String> permissionList = permissions.stream()
            .map(p -> (String)p.get("permission"))
            .filter(permission -> permission != null && !permission.trim().isEmpty())
            .collect(Collectors.toList());

        return new UserDetailsImpl(user, permissionList);
    }
} 